//
//  Array+Tool.swift
//  MetaU
//
//  Created by PerhapYs on 2022/4/18.
//

import Foundation

extension Array where Element : Equatable {

    /// 删除某个元素
    /// - Parameter element: 数组元素
    mutating func remove(_ element:Element){

        guard self.contains(element) else {
            return
        }
        guard let index = self.firstIndex(of: element) else {
            return
        }
        self.remove(at: index)
    }
    
    /// 数组去重
    /// - Returns: 去重后的数组
    func removeDuplicate() -> Array{
        
        return self.enumerated().filter({self.firstIndex(of: $0.element) == $0.offset}).map({$0.element})
    }
}

extension Array{
    
    /// 数组转Json字符串
    /// - Returns: Json字符串
    func toData() -> Data?{
        
        guard JSONSerialization.isValidJSONObject(self) else {
            return nil
        }
        do{
            let data : Data = try JSONSerialization.data(withJSONObject: self, options: [])
            return data
        }
        catch{
            print("JsonSerialization Array Encode Error:\(error)")
        }
        return nil
    }
}
extension Array where Element : Encodable{
    
    /// 可编码对象数组转字典数组
    /// - Returns: 字典数组
    func toArray() -> Array<Dictionary<String,Any>>?{
        
        let jsonEncoder = JSONEncoder()
        do{
            let jsonData = try jsonEncoder.encode(self)
            if let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? Array<Dictionary<String,Any>>{
                return jsonDic
            }
        }
        catch{
            debugPrint("JsonEncoder Error:\(error)")
        }
        return nil
    }
}
